<?php
/**
 * Created by a front-end programmer.
 * User: Xwen
 * Date: 2018/1/23
 * Time: 17:54
 * Mail:lauwencn@gmail.com
 */

final class Application
{
    public static function run(){
        self::_init();                                                  // 初始化框架
        set_error_handler(array(__CLASS__, 'error'));                   // 定义php普通错误处理函数
        register_shutdown_function(array(__CLASS__,'fatal_error'));     // 定义php致命错误处理函数
        self::_user_import();                                           // 加载用户扩展
        self::_set_url();                                               // 设置外部路径
        spl_autoload_register(array(__CLASS__, '_autoload'));           // 注册自动载入函数
        self::_create_demo();                                           // 创建初始化demo
        self::_app_run();                                               // 实例化应用类
    }

    /**
     * php致命错误处理函数
     */
    public static function fatal_error(){
        if($e = error_get_last()){
            self::error($e['type'], $e['message'], $e['file'], $e['line']);
        }
    }

    /**
     * @param $errno    错误代码
     * @param $errstr   错误信息
     * @param $errfile  文件
     * @param $errline  行数
     * 自定义错误处理
     */
    public static function error($errno,$errstr, $errfile, $errline){
        switch ($errno){
            case E_ERROR:
            case E_PARSE:
            case E_CORE_ERROR:
            case E_COMPILE_ERROR:
            case E_USER_ERROR:
                $msg = $errstr.$errfile."第{$errline}行";
                half($msg);
                break;
            case E_STRICT:
            case E_USER_WARNING:
            case E_USER_NOTICE:
            default:
                if(DEBUG){
                    include TPL_PATH.'/notice.html';
                }
                break;
        }
    }

    /**
     * 加载用户扩展文件
     */
    private static function _user_import(){
        $fileArr = C('AUTO_LOAD_FILE');
        if(is_array($fileArr)){
            foreach ($fileArr as $v){
                require_once COMMON_LIB_PATH.'/'.$v;
            }
        }
    }

    /**
     * 实例化应用类
     */
    private static function _app_run(){
        $c = isset($_GET[C('VAR_CONTROLLER')]) ? $_GET[C('VAR_CONTROLLER')] : 'Index';
        $m = isset($_GET[C('VAR_METHOD')]) ? $_GET[C('VAR_METHOD')] : 'index';
        define('CONTROLLER',$c);
        define('METHOD',$m);
        $c = $c. 'Controller';
        if(class_exists($c)){
            $obj = new $c();
            if(!method_exists($obj,$m)){
                if(method_exists($obj,'__empty')){
                    $obj->__empty();
                }else{
                    half($c."控制器中的".$m."方法不存在！");
                }
            }else{
                $obj->$m();
            }
        }else{
            $obj = new EmptyController();
            $obj->index();
        }

    }
    /**
     * @param $className
     * 自动载入功能
     * 自动载入控制器和框架自带扩展类库
     */
    private static function _autoload($className){
        switch(true){
            case strlen($className) > 10 && substr($className,-10) == 'Controller':
                $path = APP_CONTROLLER_PATH.'/'.$className.'.class.php';
                if(!is_file($path)){
                    $emptyPath = APP_CONTROLLER_PATH.'/EmptyController.class.php';
                    if(is_file($emptyPath)){
                        include $emptyPath;
                        return;
                    }else{
                        half($path."控制器未找到");
                    }
                }
                include $path;
                break;
            case strlen($className) > 5 && substr($className,-5) == 'Model':
                $path = COMMON_MODEL_PATH."/".$className.".class.php";
                include $path;
                break;
            default:
                $path = TOOL_PATH.'/'.$className.'.class.php';
                if(!is_file($path)) half($path."类未找到");
                include $path;
                break;
        }
    }

    /**
     * 创建初始化demo
     */
    private static function _create_demo(){
        $path = APP_CONTROLLER_PATH.'/IndexController.class.php';
        $str = <<<str
<?php
/**
 * Created by a front-end programmer.
 * Author: lauwen
 * Mail:lauwencn@gmail.com
 */
class IndexController extends Controller{
    public function index(){
        echo 'Welcome to LAUWENPHP!';
    }
}
?>
str;
        is_file($path) || file_put_contents($path, $str);
    }
    /**
     * 设置外部路径
     */
    private static function _set_url(){
        $path = "http://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
        $path = str_replace('\\', '/', $path);
        define('__APP__', $path);
        define('__ROOT__', dirname($path));

        define('__TPL__', __ROOT__.'/'.APP_NAME.'/Tpl');
        define('__PUBLIC__', __TPL__.'/Public');
        define('__FONT__', __PUBLIC__.'/font');
        define('__CSS__', __PUBLIC__.'/css');
        define('__JS__', __PUBLIC__.'/js');
        define('__IMAGE__', __PUBLIC__.'/image');
    }

    /**
     * 初始化框架
     */
    private static function _init(){
        // 加载框架配置项
        C(include CONFIG_PATH.'/config.php');
        //公共目录配置项
        $commonConfigPath = COMMON_CONFIG_PATH.'/config.php';
        $commonConfig = <<<str
<?php
/**
 * Created by a front-end programmer.
 * Author: lauwen
 * Mail:lauwencn@gmail.com
 */
 return array(
    //配置项  =>  配置值
 
 );


?>
str;
        is_file($commonConfigPath) || file_put_contents($commonConfigPath, $commonConfig);
        //加载公共配置项
        C(include $commonConfigPath);
        //用户配置项
        $userConfigPath = APP_CONFIG_PATH.'/config.php';
        $userConfig = <<<str
<?php
/**
 * Created by a front-end programmer.
 * Author: lauwen
 * Mail:lauwencn@gmail.com
 */
 return array(
    //配置项  =>  配置值
 
 );



?>
str;
        is_file($userConfigPath) || file_put_contents($userConfigPath, $userConfig);
        //加载用户配置项
        C(include $userConfigPath);
        //设置框架默认时区
        date_default_timezone_set(C('DEFAULT_TIME_ZONE'));
        //自动开启session
        C('SESSION_AUTO_START') && session_start();
    }

}


?>